//
//  PlayController.m
//  RTMPiOSDemo
//
//  Created by 蓝鲸 on 16/4/1.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "CWQVideoVC.h"
#import <mach/mach.h>
#import "Masonry.h"
#import "AppDelegate.h"

typedef NS_ENUM(NSInteger, ENUM_TYPE_CACHE_STRATEGY)
{
    CACHE_STRATEGY_FAST           = 1,  //极速
    CACHE_STRATEGY_SMOOTH         = 2,  //流畅
    CACHE_STRATEGY_AUTO           = 3,  //自动
};

#define CACHE_TIME_FAST             1
#define CACHE_TIME_SMOOTH           5

#define CACHE_TIME_AUTO_MIN         5
#define CACHE_TIME_AUTO_MAX         10
#define CWQDuringTime_hidden_Menu   5

@interface CWQVideoVC ()<UITextFieldDelegate, TXLivePlayListener,CWQPlayMenuDelegate,UIAlertViewDelegate>
//5秒自动隐藏菜单栏
@property(nonatomic, strong)NSTimer *timer;
@end

@implementation CWQVideoVC
{
    
    UISlider*   _playProgress;
    UILabel*    _playDuration;
    UILabel*    _playStart;
    
    BOOL        _bHWDec;
    UIButton*   _btnHWDec;
    long long   _trackingTouchTS;
    BOOL        _startSeek;
    
    UIImageView * _loadingImageView;
    BOOL        _appIsInterrupt;
    float       _sliderValue;
    TX_Enum_PlayType _playType;
    UIButton *_backBtn;
    UIView *_backView;
    BOOL    _menuHidden;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    
    //点播

    [self initUI];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initUI {
    
    _play_switch = NO;
    self.isLivePlay = NO;
    _menuHidden = NO;
    UIImage *image = [UIImage imageNamed:@"background@2x.jpg"];
    _backView = [[UIView alloc] initWithFrame:_videoWidgetFrame];
    [self.view insertSubview:_backView atIndex:0];
    _backView.layer.contents = (id)image.CGImage;
    
    int icon_length = 8;
    if (!self.isLivePlay) {
        icon_length = 6;
    } else {
        icon_length = 7;
    }
  
    _txLivePlayer = [[TXLivePlayer alloc] init];
    [_txLivePlayer setupVideoWidget:_backView.bounds containView:_backView insertIndex:0];
    [_txLivePlayer setLogLevel:LOGLEVEL_DEBUG];
    _renderFillScreen = NO;

    self.videoPause = NO;
    _trackingTouchTS = 0;
    
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"CWQPlayMenu" owner:nil options:nil]; //&1
    
    _playMenu = [views lastObject];
    _playMenu.delegate = self;
    _btnPlay = _playMenu.cwqStartPlay;
    _playProgress = _playMenu.cwqPlayProgress;
    _playDuration = _playMenu.cwqPlayDuration;
    _playStart = _playMenu.cwqSartDuration;
    [self.view addSubview:_playMenu];
    
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backBtn setFrame:CGRectMake(0, 20, 40, 40)];
    [_backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [_backBtn addTarget:self action:@selector(backVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backBtn];
    
    //loading imageview
    float width = 34;
    float height = 34;
    float offsetX = (_videoWidgetFrame.size.width - width) / 2;
    float offsetY = (_videoWidgetFrame.size.height - height) / 2;
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"loading_image0.png"],[UIImage imageNamed:@"loading_image1.png"],[UIImage imageNamed:@"loading_image2.png"],[UIImage imageNamed:@"loading_image3.png"],[UIImage imageNamed:@"loading_image4.png"],[UIImage imageNamed:@"loading_image5.png"],[UIImage imageNamed:@"loading_image6.png"],[UIImage imageNamed:@"loading_image7.png"], nil];
    _loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(offsetX, offsetY, width, height)];
    _loadingImageView.animationImages = array;
    _loadingImageView.animationDuration = 1;
    _loadingImageView.hidden = YES;
    [self.view addSubview:_loadingImageView];
    
    //判断当前网络是否是wifi
    if (!([HELNetworkManager sharedMg].netStatus == NetworkStatusWIFI)) {
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前是非WI-FI网络，是否播放？" delegate:self cancelButtonTitle:@"是" otherButtonTitles:@"否", nil];
        [alertV show];
    }else {
        
        [self cwqPlayMenuPlay:_playMenu.cwqStartPlay];
    }

}


- (void)backVC {

    if (_screenPortrait) {
        [self clickScreenOrientation:_playMenu.cwqFullScreen];
    }else {
        [_timer invalidate];
        _timer = nil;
        if (_play_switch == YES) {
            [_txLivePlayer pause];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_play_switch) {
        self.videoPause = NO;
    }
}

- (void)setVideoPause:(BOOL)videoPause {

    _videoPause = videoPause;
    if (_videoPause) {
        [_txLivePlayer pause];
        [_btnPlay setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
        [self cwq_allwaysDisplayMenu];
    }else {
        [_txLivePlayer resume];
        [_btnPlay setImage:[UIImage imageNamed:@"suspend"] forState:UIControlStateNormal];
        [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
        _menuHidden = YES;
        [self cwq_tapTV];
    }
}

-(BOOL)checkPlayUrl:(NSString*)playUrl {
    if (!([playUrl hasPrefix:@"http:"] || [playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"rtmp:"] )) {
        [self toastTip:@"播放地址不合法，目前仅支持rtmp,flv,hls,mp4播放方式!"];
        return NO;
    }
    if (self.isLivePlay) {
        if ([playUrl hasPrefix:@"rtmp:"]) {
            _playType = PLAY_TYPE_LIVE_RTMP;
        } else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && [playUrl rangeOfString:@".flv"].length > 0) {
            _playType = PLAY_TYPE_LIVE_FLV;
        } else{
            [self toastTip:@"播放地址不合法，直播目前仅支持rtmp,flv播放方式!"];
            return NO;
        }
    } else {
        if ([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) {
            if ([playUrl rangeOfString:@".flv"].length > 0) {
                _playType = PLAY_TYPE_VOD_FLV;
            } else if ([playUrl rangeOfString:@".m3u8"].length > 0){
                _playType= PLAY_TYPE_VOD_HLS;
            } else if ([playUrl rangeOfString:@".mp4"].length > 0){
                _playType= PLAY_TYPE_VOD_MP4;
            } else {
                [self toastTip:@"播放地址不合法，点播目前仅支持flv,hls,mp4播放方式!"];
                return NO;
            }
            
        } else {
            [self toastTip:@"播放地址不合法，点播目前仅支持flv,hls,mp4播放方式!"];
            return NO;
        }
    }
    
    return YES;
}




-(BOOL)startRtmp{
    NSString* playUrl = self.rtmpUrl;
    
    if (![self checkPlayUrl:playUrl]) {
        return NO;
    }
  
    
    if(_txLivePlayer != nil)
    {
        _txLivePlayer.delegate = self;
        [_txLivePlayer setupVideoWidget:_videoWidgetFrame containView:_backView insertIndex:0];

        if (_playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            _bHWDec = NO;
            _txLivePlayer.enableHWAcceleration = _bHWDec;
        }
        if (_screenPortrait) {
            [_txLivePlayer setRenderRotation:HOME_ORIENTATION_RIGHT];
            [_backView setFrame:[UIScreen mainScreen].bounds];
            
        } else {
            [_txLivePlayer setRenderRotation:HOME_ORIENTATION_DOWN];
            [_backView setFrame:_videoWidgetFrame];
        }

        for (UIView *view in [_backView subviews]) {
            if ([view isKindOfClass:NSClassFromString(@"TXVideoView")]) {
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cwq_tapTV)];
                tap.numberOfTouchesRequired = 1;
                [view addGestureRecognizer:tap];
            }
        }
        [self.view bringSubviewToFront:_playMenu];
        [self.view bringSubviewToFront:_backBtn];
        [_txLivePlayer startPlay:playUrl type:PLAY_TYPE_VOD_MP4];
        if (_renderFillScreen) {
            [_txLivePlayer setRenderMode:RENDER_MODE_FILL_SCREEN];
        } else {
            [_txLivePlayer setRenderMode:RENDER_MODE_FILL_EDGE];
        }
        self.videoPause = NO;
        [_btnPlay setImage:[UIImage imageNamed:@"suspend"] forState:UIControlStateNormal];
    }
    [self startLoadingAnimation];
    return YES;
}

- (NSTimer *)timer {
    if (!_timer) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:CWQDuringTime_hidden_Menu target:self selector:@selector(cwq_hiddenMenu) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)dealloc {
    [self stopRtmp];
    NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}

//隔5秒隐藏菜单
- (void)cwq_hiddenMenu {
    _menuHidden = NO;
    [self cwq_tapTV];
}

//点击隐藏菜单栏
- (void)cwq_tapTV {
    _menuHidden = !_menuHidden;
    CATransition *animation = [CATransition animation];
    animation.type = kCATransitionFade;
    animation.duration = .6;
    if (_menuHidden) {
        //停止定时器
        self.timer.fireDate = [NSDate distantFuture];
        if (_screenPortrait) {
            [_backBtn.layer addAnimation:animation forKey:nil];
            _backBtn.hidden = YES;
        }
        [_playMenu.layer addAnimation:animation forKey:nil];
        _playMenu.hidden = YES;
    }else {
        //启动定时器
        [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:5]];
        [_backBtn.layer addAnimation:animation forKey:nil];
        [_playMenu.layer addAnimation:animation forKey:nil];
        _backBtn.hidden = NO;
        _playMenu.hidden = NO;
        
    }
}

//现实菜单栏
- (void)cwq_allwaysDisplayMenu{
    _menuHidden = NO;
    CATransition *animation = [CATransition animation];
    animation.type = kCATransitionFade;
    animation.duration = .6;
    [_backBtn.layer addAnimation:animation forKey:nil];
    [_playMenu.layer addAnimation:animation forKey:nil];
    _backBtn.hidden = NO;
    _playMenu.hidden = NO;
    self.timer.fireDate = [NSDate distantFuture];

}

- (void)viewDidDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];

}
- (void)stopRtmp{
    [self stopLoadingAnimation];
    if(_txLivePlayer != nil)
    {
        _txLivePlayer.delegate = nil;
        [_txLivePlayer stopPlay];
        [_txLivePlayer removeVideoWidget];
    }
}


#pragma mark - ------------UIAlertViewDelegate---------------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {
        [self cwqPlayMenuPlay:_playMenu.cwqStartPlay];
    }else {
        [self cwq_allwaysDisplayMenu];
    
    }
}


#pragma mark - ---------------CWQPlayMenuDelegate---------------------
- (void)cwqPlayMenuPlay:(UIButton *)sender{

    if (_play_switch == YES)
    {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
//            if (self.videoPause) {
//                [_txLivePlayer resume];
//            } else {
//                [_txLivePlayer pause];
//            }
            self.videoPause = !self.videoPause;
            
            
        } else {
            _play_switch = NO;
            [self stopRtmp];
            [sender setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
        }
        
    }
    else
    {
        if (![self startRtmp]) {
            return;
        }
        
        [sender setImage:[UIImage imageNamed:@"suspend"] forState:UIControlStateNormal];
        _play_switch = YES;
        [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    }
    
}

//- (void)dealloc {
//    [self stopRtmp];
//}
- (void)cwqFullScreen:(UIButton *)sender{
    [self clickScreenOrientation:sender];
}

- (void)cwqSliderTouchDown:(UISlider *)sender{
    
    _startSeek = YES;
    NSLog(@"vod seek drag begin");
}
- (void)cwqSliderChangValue:(UISlider *)sender{
    [_txLivePlayer seek:_sliderValue];
    _trackingTouchTS = [[NSDate date]timeIntervalSince1970]*1000;
    _startSeek = NO;
    NSLog(@"vod seek drag end");
}
- (void)cwqSliderDrag:(UISlider *)sender{
    
    float progress = sender.value;
    int intProgress = progress + 0.5;
    _playMenu.cwqSartDuration.text = [NSString stringWithFormat:@"%02d:%02d",(int)(intProgress / 60), (int)(intProgress % 60)];
    _sliderValue = sender.value;
    
}


- (void) clickScreenOrientation:(UIButton*) sender {
    _screenPortrait = !_screenPortrait;
    [UIView animateWithDuration:.35 animations:^{
        if (_screenPortrait) {
            [sender setImage:[UIImage imageNamed:@"landscape"] forState:UIControlStateNormal];
            [_txLivePlayer setRenderRotation:HOME_ORIENTATION_RIGHT];
            [_backView setBounds:[UIScreen mainScreen].bounds];
            [self cwq_clickUpdatePlayMenuPosition];
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        } else {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
            [sender setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
            [_txLivePlayer setRenderRotation:HOME_ORIENTATION_DOWN];
            [_backView setBounds:_videoWidgetFrame];
            [self cwq_clickUpdatePlayMenuPosition];

        }
        
    }];
}

- (void)cwq_clickUpdatePlayMenuPosition {
    
     float w = 34;
     float h = 34;
     if (_screenPortrait) {
     CGFloat width = [UIScreen mainScreen].bounds.size.width;
     CGFloat height = [UIScreen mainScreen].bounds.size.height;
     [_playMenu mas_remakeConstraints:^(MASConstraintMaker *make) {
     make.centerY.mas_equalTo(self.view.mas_centerY);
     make.centerX.mas_equalTo(self.view.mas_left).offset(20);
     make.height.mas_equalTo(@40);
     make.width.mas_equalTo(@(height));
     }];
     _playMenu.transform=CGAffineTransformMakeRotation(M_PI/2);
     [_backBtn setFrame:CGRectMake(width - 40, 20, 40, 40)];
     _backBtn.transform=CGAffineTransformMakeRotation(M_PI/2);
     float offsetX = ([UIScreen mainScreen].bounds.size.width - w) / 2;
     float offsetY = ([UIScreen mainScreen].bounds.size.height - h) / 2;
     _loadingImageView.center = CGPointMake(offsetX, offsetY);
     [_backView setFrame:[UIScreen mainScreen].bounds];
         
     }else {
     
     CGFloat origionY = CGRectGetMaxY(_videoWidgetFrame) - 40;
     [_playMenu mas_remakeConstraints:^(MASConstraintMaker *make) {
     make.top.equalTo(self.view).with.offset(origionY);
     make.left.equalTo(self.view).with.offset(0);
     make.right.equalTo(self.view).with.offset(0);
     make.height.mas_equalTo(@40);
     }];
     _playMenu.transform=CGAffineTransformIdentity;
     [_backBtn setFrame:CGRectMake(0, 20, 40, 40)];
     _backBtn.transform=CGAffineTransformIdentity;
     float offsetX = (_videoWidgetFrame.size.width - w) / 2;
     float offsetY = (_videoWidgetFrame.size.height - h) / 2;
     _loadingImageView.center = CGPointMake(offsetX, offsetY);
     [_backView setFrame:_videoWidgetFrame];


     }
    if (_renderFillScreen) {
        [_txLivePlayer setRenderMode:RENDER_MODE_FILL_SCREEN];
    } else {
        [_txLivePlayer setRenderMode:RENDER_MODE_FILL_EDGE];
    }
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _vCacheStrategy.hidden = YES;
//     NSLog(@"%@",[self.view subviews]);
}


/**
 @method 获取指定宽度width的字符串在UITextView上的高度
 @param textView 待计算的UITextView
 @param Width 限制字符串显示区域的宽度
 @result float 返回的高度
 */
- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}

- (void) toastTip:(NSString*)toastInfo
{
    CGRect frameRC = [[UIScreen mainScreen] bounds];
    frameRC.origin.y = frameRC.size.height - 110;
    frameRC.size.height -= 110;
    __block UITextView * toastView = [[UITextView alloc] init];
    
    toastView.editable = NO;
    toastView.selectable = NO;
    
    frameRC.size.height = [self heightForString:toastView andWidth:frameRC.size.width];
    
    toastView.frame = frameRC;
    
    toastView.text = toastInfo;
    toastView.backgroundColor = [UIColor whiteColor];
    toastView.alpha = 0.5;
    
    [self.view addSubview:toastView];
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(){
        [toastView removeFromSuperview];
        toastView = nil;
    });
}

#pragma ###TXLivePlayListener


-(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param;
{
    NSDictionary* dict = param;
    if (!self.timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:CWQDuringTime_hidden_Menu target:self selector:@selector(cwq_hiddenMenu) userInfo:nil repeats:YES];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if (EvtID == PLAY_EVT_PLAY_BEGIN) {
            [self stopLoadingAnimation];
        } else if (EvtID == PLAY_EVT_PLAY_PROGRESS && !_startSeek) {
            // 避免滑动进度条松开的瞬间可能出现滑动条瞬间跳到上一个位置
            long long curTs = [[NSDate date]timeIntervalSince1970]*1000;
            if (llabs(curTs - _trackingTouchTS) < 500) {
                return;
            }
            _trackingTouchTS = curTs;
            
            float progress = [dict[EVT_PLAY_PROGRESS] floatValue];
            int intProgress = progress + 0.5;
            if (!self.videoPause) {

                _playStart.text = [NSString stringWithFormat:@"%02d:%02d", (int)(intProgress / 60), (int)(intProgress % 60)];
                [_playProgress setValue:progress];
            }
            
            float duration = [dict[EVT_PLAY_DURATION] floatValue];
            int intDuration = duration + 0.5;
            if (duration > 0 && _playProgress.maximumValue != duration) {
                [_playProgress setMaximumValue:duration];
                _playDuration.text = [NSString stringWithFormat:@"%02d:%02d", (int)(intDuration / 60), (int)(intDuration % 60)];
            }
            return ;
        } else if (EvtID == PLAY_ERR_NET_DISCONNECT || EvtID == PLAY_EVT_PLAY_END) {
            [self stopRtmp];
            _play_switch = NO;
            [_btnPlay setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
            [_playProgress setValue:0];
            _playStart.text = @"00:00";
            self.videoPause = NO;
            [self cwq_allwaysDisplayMenu];
        } else if (EvtID == PLAY_EVT_PLAY_LOADING){
            [self startLoadingAnimation];
        }
    });
}

-(void) onNetStatus:(NSDictionary*) param
{
    NSDictionary* dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        int netspeed  = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_SPEED] intValue];
        int vbitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_BITRATE] intValue];
        int abitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_AUDIO_BITRATE] intValue];
        int cachesize = [(NSNumber*)[dict valueForKey:NET_STATUS_CACHE_SIZE] intValue];
        int dropsize  = [(NSNumber*)[dict valueForKey:NET_STATUS_DROP_SIZE] intValue];
        int jitter    = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_JITTER] intValue];
        int fps       = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_FPS] intValue];
        int width     = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_WIDTH] intValue];
        int height    = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_HEIGHT] intValue];
        float cpu_usage = [(NSNumber*)[dict valueForKey:NET_STATUS_CPU_USAGE] floatValue];
        NSString *serverIP = [dict valueForKey:NET_STATUS_SERVER_IP];
        int codecCacheSize = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_CACHE] intValue];
        int nCodecDropCnt = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_DROP_CNT] intValue];
        
        NSString* log = [NSString stringWithFormat:@"CPU:%.1f%%\tRES:%d*%d\tSPD:%dkb/s\nJITT:%d\tFPS:%d\tARA:%dkb/s\nQUE:%d|%d\tDRP:%d|%d\tVRA:%dkb/s\nSVR:%@\t",
                         cpu_usage*100,
                         width,
                         height,
                         netspeed,
                         jitter,
                         fps,
                         abitrate,
                         codecCacheSize,
                         cachesize,
                         nCodecDropCnt,
                         dropsize,
                         vbitrate,
                         serverIP];
        [_statusView setText:log];
        
    });
}

-(void) startLoadingAnimation
{
    if (_loadingImageView != nil) {
        _loadingImageView.hidden = NO;
        [_loadingImageView startAnimating];
    }
}

-(void) stopLoadingAnimation
{
    if (_loadingImageView != nil) {
        _loadingImageView.hidden = YES;
        [_loadingImageView stopAnimating];
    }
}

//在低系统（如7.1.2）可能收不到这个回调，请在onAppDidEnterBackGround和onAppWillEnterForeground里面处理打断逻辑
- (void) onAudioSessionEvent: (NSNotification *) notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        if (_play_switch == YES && _appIsInterrupt == NO) {
            if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
                if (!self.videoPause) {
                    [_txLivePlayer pause];
                }
            }
            _appIsInterrupt = YES;
        }
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            if (_play_switch == YES && _appIsInterrupt == YES) {
                if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
                    if (!self.videoPause) {
                        [_txLivePlayer resume];
                    }
                }
                _appIsInterrupt = NO;
            }
        }
    }
}

- (void)onAppDidEnterBackGround:(UIApplication*)app {
    if (_play_switch == YES && _appIsInterrupt == NO) {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            if (!self.videoPause) {
                [_txLivePlayer pause];
            }
        }
        _appIsInterrupt = YES;
    }
}

- (void)onAppWillEnterForeground:(UIApplication*)app {
    _menuHidden = YES;
    [self cwq_tapTV];
    if (_play_switch == YES && _appIsInterrupt == YES) {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            if (!self.videoPause) {
                [_txLivePlayer resume];
            }
        }
        _appIsInterrupt = NO;
    }
}



@end
